from trees.models import Plant, Species
from trees.forms import RxForm, InquiryForm
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.views.generic.simple import direct_to_template
from django.core.urlresolvers import reverse
from django.db.models import Count

from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Q


def home(request):
    """
    Homepage overview
    """
    
    treecount = Plant.objects.all().count()
    speciescount = Species.objects.all().count()    

    return render_to_response('home.html', {
        'treecount':treecount,
        'speciescount':speciescount,        
        
    	}, 
    	context_instance=RequestContext(request)
    	) 


def stats(request):
    """
    Statistical breakdowns
    """
    
    treecount = Plant.objects.all().count()
    speciescount = Species.objects.all().count()   
    
    tree_type_count = Plant.objects.filter(plant_type=1).count()
    landscape_type_count = treecount - tree_type_count
    
    dpw_count = Plant.objects.filter(caretaker=1).count()
    private_count = treecount - dpw_count
              

    
    # The realtime way to do it, but VERY slow - use maintenance script lastcount.py instead to populate count field in db
    # popular_species = Species.objects.annotate(num_plants=Count('plant')).filter(num_plants__gt=300).order_by('num_plants')
    popular_species = Species.objects.filter().exclude(id=106).order_by('-lastcount')[:15]

    most_pop = Species.objects.filter().order_by('-lastcount')[:1][0]   

    # Build data for charts
    s_counts = []
    s_labels = []
    for s in popular_species:
        s_counts.append(int(s.lastcount)/100)
        s_labels.append(s.common_name)

    return render_to_response('stats.html', 
            locals(),    
     	context_instance=RequestContext(request)
    	)




def species_all(request):
    """
    Simple view of all tree species
    """

    species_all = Species.objects.all().order_by('-lastcount')

    return render_to_response('species_all.html', {

        'species_all':species_all,    
        
    	}, 
    	context_instance=RequestContext(request)
    	)
    	
    	
def plants_all(request):
    """
    Simple view of all plants
    """

    plants_all = Plant.objects.all().order_by('-address')[:100]

    return render_to_response('plants_all.html', {

        'plants_all':plants_all,    
        
    	}, 
    	context_instance=RequestContext(request)
    	)    	


    
def plants_index(request):
    """
    Searchable index/table of all plants.
    
    """
    # Comment/uncomment during debug:
    # request.session.clear()
    
    # Check for change to show/hide non-webcast first, before dealing with search
    # if request.POST:    
    #     try:    
    #         if request.POST['hide_nw']:
    #             request.session.clear()
    #     except:
    #         pass
    # 
    #     try:
    #         if request.POST['inc_nw']:
    #             request.session['inc_nw'] = True
    #     except:
    #         pass
    #                             
    #         return HttpResponseRedirect('')
          
            
    # This if/else within a try/except is less than ideal but the only way I was able to get it working...    
    try:
        # Handle search results first. 
        # Make sure q isn't empty (user clicks Search without a term)
        if len(request.GET['q'].strip()) > 0 :
            query_string = request.GET['q']

            plants = Plant.objects.filter(
                Q(specie__latin_name__icontains=query_string) |
                Q(specie__common_name__icontains=query_string) |                
                Q(address__icontains=query_string)              
            )
            
        else:
            plants = Plant.objects.all()
            query_string = None
            
    except :
        query_string = None
        plants = Plant.objects.all()


    # Whether queryset comes from search or not, filter the results by same criteria
    # plants = plants.filter() # Post filter on other criteria if necessary
    
    # Selectively include non-webcasts depending on state of the session
    # if not request.session.get('inc_nw'):
    #     presentations = presentations.filter(has_webcast=True)
    
    # Apply the ordering last
    plants = plants.order_by('-address')

    numset = plants.all().count()
    
    # Run presentations through the paginator
    paginator = Paginator(plants, 100)
    
    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        plants = paginator.page(page)
    except (EmptyPage, InvalidPage):
        plants = paginator.page(paginator.num_pages)
    
    

    return render_to_response( 'plants_index.html', 
        {
            'plants': plants,
            'numset': numset,
            'query_string':query_string,
        }, context_instance=RequestContext(request),
    )    

    
def species_detail(request,species_id):
    '''Details on a particular species'''

    specie = get_object_or_404(Species,id=species_id)

    return render_to_response('species_detail.html', {
        's':specie,    
    	}, 
    	context_instance=RequestContext(request)
    	)
    	
    	
def plant_detail(request,plant_id):
    '''Details on a particular plant'''
    plant = get_object_or_404(Plant,id=plant_id)

    # For passing to Google Maps
    address_string = plant.address.replace(" ","+")
    
    return render_to_response('plant_detail.html', {
        'p':plant,    
        'address_string':address_string,
    	}, 
    	context_instance=RequestContext(request)
    	)    	
    	
    	
def plant_rx(request,plant_id):
    '''Let the city know a particular plant needs help'''
    plant = get_object_or_404(Plant,id=plant_id)


    if request.POST:
            form = RxForm(request.POST)

            if form.is_valid():
                # Don't commit the save until we've added in the fields we need to set
                item = form.save(commit=False)
                item.plant = Plant.objects.get(id=plant_id)
                # ...
                item.save()
                
                # Send email
                # email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': item.title })                    
                # email_body = render_to_string("todo/email/assigned_body.txt", { 'task': item, 'site': current_site, })
                # try:
                #     send_mail(email_subject, email_body, item.created_by.email, [item.assigned_to.email], fail_silently=False)
                # except:
                #     request.user.message_set.create(message="Task saved but mail not sent. Contact your administrator." )                

                request.user.message_set.create(message="Your TreeRx ticket has been submitted. We'll get back to you when the tree has been inspected.")
                return direct_to_template(request, 'plant_rx_thanks.html')
        
        
    else:
        form = RxForm()

    
    return render_to_response('plant_rx.html', {
        'p':plant,
        'form':form,    

    	}, 
    	context_instance=RequestContext(request)
    	)    	    	

# def new_plant(request):
#     """
#     Request a new tree.
#     """
#     return render_to_response('new_plant.html',  
#     	context_instance=RequestContext(request)
#     	) 

def new_plant(request):
    '''Request a new tree.'''


    if request.POST:
            form = InquiryForm(request.POST)

            if form.is_valid():
                item = form.save(commit=False)
                item.save()
                
                # Send email
          
                return direct_to_template(request, 'request_thanks.html')
        
        
    else:
        form = InquiryForm()

    
    return render_to_response('new_plant.html',  
    	context_instance=RequestContext(request)
    	) 